import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer_0602 {
    DatagramSocket socket = null;

    public UdpEchoServer_0602 (int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);

            String request = new String(requestPacket.getData(),0,requestPacket.getLength());

            String response = process(request);

            /*getData().length 返回的是数据包缓冲区的总容量（创建时指定的1024字节）
              getLength() 返回的是实际接收到的数据长度（可能远小于缓冲区大小）*/
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s : %S] request: %s, response: %s",requestPacket.getAddress(),
                    requestPacket.getPort(),request,response);
            System.out.println();
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer_0602 udpEchoServer0602 = new UdpEchoServer_0602(9090);
        udpEchoServer0602.start();
    }

}
